/*
 * Copyright (C) 2011 JiangHongTiao
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.paris.webclient.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import sk.lieskove.jianghongtiao.common.enums.MimeTypeEnum;
import sk.lieskove.jianghongtiao.common.utils.FileUtils;
import sk.lieskove.jianghongtiao.common.utils.PropertiesUtils;
import sk.lieskove.jianghongtiao.common.utils.ZipUtils;
import sk.lieskove.jianghongtiao.paris.webclient.export.ArffExport;
import sk.lieskove.jianghongtiao.paris.webclient.model.DocumentManager;
import sk.lieskove.jianghongtiao.paris.webclient.persistence.ClassificationItem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.stripes.validation.Validate;
import sk.lieskove.jianghongtiao.common.utils.Array;

/**
 * 
 * @author xjuraj e-mail: jjurco.sk_gmail.com
 */
@UrlBinding(value = "/export/{$event}")
public class ExportActionBean extends AbstractActionBean implements Serializable {
    
    private transient PropertiesUtils pu = new PropertiesUtils(ExportActionBean.class);
    @SpringBean
    private DocumentManager documentManager;
    
    private String language;
    private List<String> trainDocTypes;
    private List<String> testDocTypes;
    @Validate(minvalue=1, maxvalue=99, required=false)
    private Integer baseline = 60;
    @Validate(minvalue=1, maxvalue=9999, required=false)
    private Integer wordsToKeep = 500;
    
    @DefaultHandler
    public Resolution export(){
        List langList = documentManager.getUsedLanguageList();
        List docTypeList = documentManager.getUsedClasses();
        Collections.sort(langList);
        this.getContext().getRequest().setAttribute("langList", langList);
        this.getContext().getRequest().setAttribute("docTypeList", docTypeList);
        return new ForwardResolution("/WEB-INF/pages/export.jsp");
    }
    
    
    private List<ClassificationItem> getLearningSet(List<String> docTypeList){
        //language
        //baseline
        //training/test doc types
        //select documents by language and docType is in training/test set
        //query for each docType from training/test set
        //count baseline, select randomly num of documents
        if((docTypeList == null) || docTypeList.isEmpty()){
            return null;
        }
        
        List<ClassificationItem> result = new ArrayList<ClassificationItem>();
        Map<String, List<ClassificationItem>> docTypeCI = new HashMap<String, List<ClassificationItem>>();
        int max = 0;
        int count = 0;
        for (String docType : docTypeList) {
            List<ClassificationItem> items = documentManager.getNotExcludedByLangDocType(language, docType);
            max = Math.max(max, items.size());
            count = count + items.size();
            docTypeCI.put(docType, items);
        }
        double a = baseline/100.0;
        double b = count-max;
        int maxItems = (int) Math.round((-1.0*a*b)/(a-1.0));
        for (String docType : docTypeList) {
            List<ClassificationItem> items = docTypeCI.get(docType);
            if(items.size() > maxItems){ 
                result.addAll(Array.randomSubset(items, maxItems));
            } else {
                result.addAll(items);
            }
        }
        return result;
    }
    
    public Resolution splitByLang(){
        List<String> langList = documentManager.getUsedLanguageList();
        List<String> typeList = documentManager.getUsedClasses();
        
        File trainSetFile = ArffExport.exportAsArff(langList, typeList, 
                getLearningSet(trainDocTypes), language+"-training-set", 
                wordsToKeep, "");
        File testSetFile = ArffExport.exportAsArff(langList, typeList, 
                getLearningSet(testDocTypes), language+"-test-set",
                wordsToKeep, "");
        
        
        File zipOut = FileUtils.getTempFile("zipArff_"+language, ".zip");
        ZipUtils.zipFiles(zipOut, trainSetFile, testSetFile);
        
        Resolution response = new ForwardResolution("/WEB-INF/pages/internalServerError.jsp");
        try {
            StreamingResolution streamingResolution = new StreamingResolution(
                    MimeTypeEnum.application_zip.value(),
                    new FileInputStream(zipOut));
            streamingResolution.setFilename("paris-arff-"+language+".zip");
            streamingResolution.setLength(zipOut.length());
            response = streamingResolution;
        } catch (FileNotFoundException e) {
            log.error("Output zipped ARFF file was not found: "+zipOut.getAbsolutePath());
        } finally {
            return response;
        }
    }
    
    /**
     * export database data in zipped ARFF file
     * @return ZIP file as resolution or internal server error in the case of failure
     */
    public Resolution exportArff(){
        List<String> langList = documentManager.getUsedLanguageList();
        List<String> typeList = documentManager.getUsedClasses();
        
        List<String> searchedQueries = documentManager.getListOfSearchedQueries();
        ArrayList<File> arffs = new ArrayList<File>();
        for (String query : searchedQueries) {
            List<ClassificationItem> itemList = documentManager.getNotExcludedProcessed(query);
            File arff = ArffExport.exportAsArff(langList, typeList, itemList, 
                    query, wordsToKeep, "");
            arffs.add(arff);
        }
        File zipOut = FileUtils.getTempFile("zipArff", ".zip");
        ZipUtils.zipFiles(zipOut, arffs.toArray(new File[0]));
        
        Resolution response = new ForwardResolution("/WEB-INF/pages/internalServerError.jsp");
        try {
            StreamingResolution streamingResolution = new StreamingResolution(
                    MimeTypeEnum.application_zip.value(),
                    new FileInputStream(zipOut));
            streamingResolution.setFilename("paris-arff-data-export.zip");
            streamingResolution.setLength(zipOut.length());
            response = streamingResolution;
        } catch (FileNotFoundException e) {
            log.error("Output zipped ARFF file was not found: "+zipOut.getAbsolutePath());
        } finally {
            return response;
        }
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public List getTestDocTypes() {
        return testDocTypes;
    }

    public void setTestDocTypes(List testDocTypes) {
        this.testDocTypes = testDocTypes;
    }

    public List getTrainDocTypes() {
        return trainDocTypes;
    }

    public void setTrainDocTypes(List trainDocTypes) {
        this.trainDocTypes = trainDocTypes;
    }

    public Integer getBaseline() {
        return baseline;
    }

    public void setBaseline(Integer baseline) {
        this.baseline = baseline;
    }

    public Integer getWordsToKeep() {
        return wordsToKeep;
    }

    public void setWordsToKeep(Integer wordsToKeep) {
        this.wordsToKeep = wordsToKeep;
    }

    
}
